<template>
  <div class="profile-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="个人中心"
      fixed
      placeholder
      :border="false"
    />

    <div class="content-wrapper">
      <!-- 用户信息卡片 -->
      <div class="user-card">
        <div class="user-avatar">
          <van-icon name="manager-o" size="48" color="white" />
        </div>
        <div class="user-info">
          <h2 class="username">{{ userInfo?.username || '用户' }}</h2>
          <p class="user-role">系统管理员</p>
        </div>
      </div>

      <!-- 功能菜单 -->
      <div class="menu-section">
        <van-cell-group inset>
          <van-cell
            title="Google验证器"
            :label="totpEnabled ? '已启用' : '未启用'"
            is-link
            @click="showTotpDialog = true"
          >
            <template #icon>
              <van-icon name="shield-o" class="menu-icon" color="#1989fa" />
            </template>
            <template #right-icon>
              <van-switch v-model="totpEnabled" size="20" @click.stop="toggleTotp" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 关于信息 -->
      <div class="menu-section">
        <van-cell-group inset>
          <van-cell
            title="应用版本"
            value="1.0.0"
          >
            <template #icon>
              <van-icon name="info-o" class="menu-icon" color="#07c160" />
            </template>
          </van-cell>
          <van-cell
            title="在线文档"
            is-link
            @click="openDocs"
          >
            <template #icon>
              <van-icon name="notes-o" class="menu-icon" color="#ff976a" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 退出登录 -->
      <div class="logout-section">
        <van-button
          block
          round
          type="danger"
          @click="handleLogout"
        >
          退出登录
        </van-button>
      </div>

      <!-- 版权信息 -->
      <div class="copyright">
        <p>&copy; 2025 老薛SSH工具</p>
        <p>Mobile Version</p>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTab" fixed placeholder>
      <van-tabbar-item icon="cluster-o" to="/servers">服务器</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>

    <!-- Google验证器弹窗 -->
    <van-popup
      v-model:show="showTotpDialog"
      round
      closeable
      position="center"
      :style="{ padding: '20px', width: '85%' }"
    >
      <div class="totp-dialog">
        <h3>Google验证器设置</h3>
        
        <template v-if="!totpEnabled">
          <p class="tip">启用两步验证可以增强账户安全性</p>
          
          <div v-if="qrCodeUrl" class="qr-section">
            <img :src="qrCodeUrl" alt="QR Code" class="qr-code" />
            <p class="qr-tip">请使用Google Authenticator扫描二维码</p>
            
            <van-field
              v-model="totpToken"
              label="验证码"
              placeholder="输入6位验证码"
              type="digit"
              maxlength="6"
            />
            
            <van-button
              block
              type="primary"
              @click="enableTotp"
              :loading="enableLoading"
            >
              启用验证器
            </van-button>
          </div>
          
          <van-button
            v-else
            block
            type="primary"
            @click="generateQRCode"
            :loading="qrLoading"
          >
            生成二维码
          </van-button>
        </template>
        
        <template v-else>
          <p class="tip success">Google验证器已启用</p>
          <van-button
            block
            type="danger"
            @click="disableTotp"
            :loading="disableLoading"
          >
            禁用验证器
          </van-button>
        </template>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { useAuthStore } from '@/stores/auth'
import authAPI from '@/api/auth'

const router = useRouter()
const authStore = useAuthStore()

// 状态
const activeTab = ref(1)
const userInfo = ref(null)
const totpEnabled = ref(false)
const showTotpDialog = ref(false)
const qrCodeUrl = ref('')
const totpToken = ref('')
const qrLoading = ref(false)
const enableLoading = ref(false)
const disableLoading = ref(false)

// 加载用户信息
const loadUserInfo = () => {
  const user = localStorage.getItem('user')
  if (user) {
    userInfo.value = JSON.parse(user)
  }
}

// 检查TOTP状态
const checkTotpStatus = async () => {
  try {
    const response = await authAPI.checkTOTPStatus()
    totpEnabled.value = response.enabled
  } catch (error) {
    console.error('❌ 检查TOTP状态失败:', error)
  }
}

// 切换TOTP
const toggleTotp = () => {
  if (!totpEnabled.value) {
    showTotpDialog.value = true
  }
}

// 生成QR码
const generateQRCode = async () => {
  try {
    qrLoading.value = true
    console.log('📱 生成QR码')
    
    const response = await authAPI.generateTOTP()
    qrCodeUrl.value = response.qrCode
    
    showToast({ type: 'success', message: 'QR码生成成功', position: 'top' })
  } catch (error) {
    console.error('❌ 生成QR码失败:', error)
    showToast('生成QR码失败')
  } finally {
    qrLoading.value = false
  }
}

// 启用TOTP
const enableTotp = async () => {
  if (!totpToken.value || totpToken.value.length !== 6) {
    showToast('请输入6位验证码')
    return
  }
  
  try {
    enableLoading.value = true
    console.log('📱 启用TOTP')
    
    await authAPI.enableTOTP(totpToken.value)
    
    totpEnabled.value = true
    showTotpDialog.value = false
    qrCodeUrl.value = ''
    totpToken.value = ''
    
    showToast({ type: 'success', message: 'Google验证器已启用', position: 'top' })
  } catch (error) {
    console.error('❌ 启用TOTP失败:', error)
    showToast('验证码错误或启用失败')
  } finally {
    enableLoading.value = false
  }
}

// 禁用TOTP
const disableTotp = async () => {
  try {
    await showConfirmDialog({
      title: '确认禁用',
      message: '禁用后登录将不再需要验证码，确定要禁用吗？'
    })
    
    disableLoading.value = true
    console.log('📱 禁用TOTP')
    
    await authAPI.disableTOTP()
    
    totpEnabled.value = false
    showTotpDialog.value = false
    
    showToast({ type: 'success', message: 'Google验证器已禁用', position: 'top' })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('❌ 禁用TOTP失败:', error)
      showToast('禁用失败')
    }
  } finally {
    disableLoading.value = false
  }
}

// 打开文档
const openDocs = () => {
  showToast('文档功能开发中')
}

// 退出登录
const handleLogout = async () => {
  try {
    await showConfirmDialog({
      title: '确认退出',
      message: '确定要退出登录吗？'
    })
    
    console.log('📱 退出登录')
    
    // 清除本地数据
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    authStore.clearUser()
    
    showToast({ type: 'success', message: '已退出登录', position: 'top' })
    
    setTimeout(() => {
      router.replace('/login')
    }, 500)
  } catch (error) {
    // 用户取消
  }
}

// 页面加载
onMounted(() => {
  console.log('📱 个人中心页加载')
  loadUserInfo()
  checkTotpStatus()
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 50px;
}

/* 内容区域 */
.content-wrapper {
  padding: 16px;
}

/* 用户卡片 */
.user-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 32px 20px;
  text-align: center;
  margin-bottom: 16px;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

.user-avatar {
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
  backdrop-filter: blur(10px);
}

.user-info {
  color: white;
}

.username {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 8px 0;
}

.user-role {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

/* 菜单区域 */
.menu-section {
  margin-bottom: 16px;
}

.menu-icon {
  margin-right: 12px;
  font-size: 20px;
}

/* 退出登录 */
.logout-section {
  margin-top: 32px;
  padding: 0 16px;
}

/* 版权信息 */
.copyright {
  text-align: center;
  margin-top: 32px;
  color: #969799;
  font-size: 12px;
}

.copyright p {
  margin: 4px 0;
}

/* TOTP对话框 */
.totp-dialog {
  text-align: center;
  background: white;
  color: #323233;
}

.totp-dialog h3 {
  font-size: 18px;
  margin-bottom: 16px;
  color: #323233;
  font-weight: 600;
}

.tip {
  font-size: 14px;
  color: #646566 !important;
  margin: 16px 0;
  line-height: 1.6;
}

.tip.success {
  color: #07c160 !important;
  font-weight: 500;
}

.qr-section {
  margin: 20px 0;
}

.qr-code {
  width: 200px;
  height: 200px;
  margin: 0 auto 16px;
  border: 1px solid #ebedf0;
  border-radius: 8px;
  padding: 10px;
  background: white;
}

.qr-tip {
  font-size: 13px;
  color: #969799;
  margin-bottom: 20px;
}

/* Vant样式覆盖 */
:deep(.van-nav-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.van-nav-bar__title) {
  color: white;
  font-weight: bold;
}

:deep(.van-tabbar) {
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.van-cell__title) {
  font-weight: 500;
}

:deep(.van-cell__label) {
  font-size: 12px;
}
</style>

